from multiprocessing import Pool,Manager
from concurrent.futures import ProcessPoolExecutor
import os

def worker(task_id, shared_list):
    """子进程：处理任务并把结果放入共享列表"""
    process_id = os.getpid()
    result = f"任务 {task_id} 由进程 {process_id} 处理完成"
    shared_list.append(result)

if __name__ == '__main__':
    # 创建一个Manager对象，用于进程间共享数据
    with Manager() as manager:
        # 创建一个共享列表
        shared_list = manager.list()

        # 创建有四个进程的进程池
        # 方式一：使用ProcessPoolExecutor创建进程池
        # with语句会自动等待所有任务完成后再退出上下文，这是它相比于Pool更简洁的地方
        with ProcessPoolExecutor(max_workers=4) as executor:
            tasks = [executor.submit(worker, i, shared_list) for i in range(10)]

        # 方式二：下面使用Pool创建进程池
        # with Pool(processes=4) as pool:
            # # 使用进程池中进程来执行任务
            # for i in range(10):
            #     pool.apply_async(worker, args=(i, shared_list))
            # # 关闭进程池，阻止任务提交
            # pool.close()
            # # 等待所有子进程完成
            # pool.join()

            # tasks = [pool.apply_async(worker, args=(i, shared_list)) for i in range(10)]
            # # 等待所有任务完成
            # for task in tasks:
            #     task.wait()


        # 打印共享列表中的所有结果
        print(shared_list)